package com.example.hegel.goddess;

import android.app.DownloadManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.google.common.collect.Lists;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;



public class WebService {

    public static final String DIR_TYPE = Environment.DIRECTORY_PICTURES + "/1024";

//    private final SimpleDateFormat formatDir;

    private SimpleDateFormat formatBatch;

//    private FileService fileService;

    public WebService() {
        this.formatBatch = new SimpleDateFormat("MMdd_HHmmss", Locale.CHINA);
//        this.fileService = new FileService();
    }

    private void submit(DownloadManager downloadManager, List<String> urls) {
        final String batch = formatBatch.format(new Date());
        String dirType = DIR_TYPE + "/" + getSubDir();
        for (int i = 0; i < urls.size(); i++) {
            submit(downloadManager, urls.get(i), dirType, String.format(Locale.CHINA,"%s_%03d.jpg", batch, i));
        }
    }


    private void submit(DownloadManager downloadManager, String spec, String dirType, String filename) {
        Uri uri = Uri.parse(spec);
        DownloadManager.Request request = new DownloadManager.Request(uri);

        final String description = new File(uri.getPath()).getName();

        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
                .setAllowedOverRoaming(false)
                .setDescription(description)
                .setTitle(filename)
                .setDestinationInExternalPublicDir(dirType, filename);
        request.allowScanningByMediaScanner();

        downloadManager.enqueue(request);
    }

    @NonNull
    private List<String> getImgSrc(String spec) throws IOException {
        Document doc = Jsoup.connect(spec).get();
        Elements pictures = doc.select("#read_tpc img");

        List<String> retVal = new ArrayList<>(pictures.size());
        for (Element img : pictures) {
            String src = img.attr("src");
            if (src.endsWith(".jpg")) {
                retVal.add(src);
            }
        }
        return Lists.reverse(retVal);
    }


    public void submit(DownloadManager manager, String text, Context context) {
        //observeOn, 指定后面的操作在哪个线程上面执行
        final Consumer<List<String>> onNext = urls -> {
            submit(manager, urls);
        };

        Action onComplete = () -> {
            Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();
//            Uri uri = Uri.fromFile(getImageRoot());
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, getImageRoot()));
        };

        Consumer<Throwable> onError = throwable -> Toast.makeText(context, "提交失败:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();

        Flowable.just(text)
                .observeOn(Schedulers.io())
                .map(spec -> getImgSrc(spec))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete(onComplete)
                .doOnError(onError)
                .observeOn(Schedulers.computation())
                .subscribe(onNext);
    }

    @NonNull
    public String getClipDataText(ClipboardManager clipboardManager) {
        ClipData clip = clipboardManager.getPrimaryClip();
        if (clip == null || clip.getItemCount() == 0) {
            return "";
        }
        return clip.getItemAt(0).getText().toString();
    }

    public String getSubDir() {
        return new SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(new Date());
    }

    @NonNull
    public Uri getImageRoot() {
        return Uri.parse(Environment.getExternalStorageDirectory() + File.separator + WebService.DIR_TYPE + File.separator + getSubDir());
    }
}
